<?php
class ChownPassCtl extends BaseCtl {
	
	public function ChownPassCtl(){
		parent::BaseCtl();
	}
	
	public function submit(){
		try {
			$form = $this->getChownPassForm(); 
			
			// depending on the readonly flag, will first check it, then change it
			$old = $form->getOld();
			$pass = $form->getPass();
			$repeat = $form->getRepeat();
			$readonly = $form->isReadonly();
			
			$pass = trim($pass);
			$repeat = trim($repeat);
			
			if($pass == $repeat){
				$user = HtmlUtil::getSessionUser()->getUser();
				$password = $user->getPass();
				$ropass = $user->getPassRo();
				
				$id = $user->getId();
				
				$check = false; 
				if($readonly){
					$check = $this->checkPassword($old, $ropass);
				}
				else {
					$check = $this->checkPassword($old, $password);
				}
				
				if($check){
					$service = new Service();
					
					$change = trim($pass);
					$change = $this->isEmpty($change) ? '' : md5($change);
					
					if($readonly){
						$service->changeReadonlyPassword($id, $change);
						$user->setPassRo($change);
					}
					else {
						$service->changeEditPassword($id, $change);
						$user->setPass($change);
					}
					
					HtmlUtil::addMessage('Password change successful');
					
					$this->redirect('profile.php');
				}
				else {
					throw new Exception('Invalid credentials');
				}
			}
			else {
				throw new Exception('The two provided passwords don\'t match');
			}
			
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function cancel(){
		try {
			$this->redirect('profile.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
    public function isPostback(){
    	return 'chownpass' == $this->getPost('pagename');
    }

    public function loadData(){
    	$form = $this->getChownPassForm();
    	
    	$form->setOld($this->getPost('old')); 
    	$form->setPass($this->getPost('pass'));
    	$form->setRepeat($this->getPost('repeat'));
    	$form->setReadonly('on' == $this->getPost('readonly'));
    }
} 
?>